import { Kysely, MysqlDialect } from 'kysely';
import mysql from 'mysql2';
import { SysRole } from '../domain/sys_role';
import { SysUser } from '@common/domain/sys_user';
import { GCategory } from '../domain/g_category';
import { GCategoryDesc } from '../domain/g_category_desc';
import { GNews } from '../domain/g_news';
import { GNewsDesc } from '../domain/g_news_desc';
import { SysMenu } from '../domain/sys_menu';
import { SysRoleMenu } from '@common/domain/sys_role_menu';
import { SysUserRole } from '@common/domain/sys_user_role';
import { SysLogininfor } from '@common/domain/sys_logininfor';

export interface Database {
  sys_user: SysUser;
  sys_role: SysRole;
  sys_user_role: SysUserRole;
  sys_menu: SysMenu;
  sys_role_menu: SysRoleMenu;
  sys_logininfor: SysLogininfor;
  sys_oper_log: SysOperLog;
  g_category: GCategory;
  g_category_desc: GCategoryDesc;
  g_news: GNews;
  g_news_desc: GNewsDesc;
}

const dialect = new MysqlDialect({
  pool: mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  })
});

export const db = new Kysely<Database>({ 
  dialect,
  // ✅ 启用日志：显示执行的 SQL
  log: (event) => {
    if (event.level === 'query') {
      console.log('>>> SQL:', event.query.sql);
      console.log('>>> Params:', event.query.parameters);
      console.log('>>> Use Time:', event.queryDurationMillis, 'ms');
    } else if (event.level === 'error') {
      console.error('❌ SQL Error:', event.error);
    }
  }
 }); 